<script setup lang="ts">
import { ref, watch, h } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import { fetchJobInstanceList, rerunJobInstance, stopJobInstance, syncJobInstanceStatus } from '@/service/api';
import { useTable } from '@/hooks/common/table';
import InstanceLogModal from './instance-log-modal.vue';

defineOptions({
  name: 'JobInstanceDrawer'
});

interface Props {
  jobId?: number;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const logModalVisible = ref(false);
const selectedInstanceId = ref<number>();

const { columns, data, loading, pagination, getData, getDataByPage, mobilePagination } = useTable({
  apiFn: fetchJobInstanceList,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    jobId: props.jobId
  },
  immediate: false,
  columns: () => [
    {
      key: 'id',
      title: 'ID',
      align: 'center',
      width: 80
    },
    {
      key: 'jobName',
      title: '作业名称',
      align: 'center',
      minWidth: 150
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      width: 100,
      render: row => {
        const statusMap: Record<string, { label: string; type: NaiveUI.ThemeColor }> = {
          RUNNING: { label: '运行中', type: 'info' },
          SUCCESS: { label: '成功', type: 'success' },
          FAILED: { label: '失败', type: 'error' },
          STOPPED: { label: '已停止', type: 'warning' }
        };
        const config = statusMap[row.status] || { label: row.status, type: 'default' };
        return h(NTag, { type: config.type }, () => config.label);
      }
    },
    {
      key: 'triggerType',
      title: '触发类型',
      align: 'center',
      width: 100,
      render: row => {
        const typeMap: Record<string, string> = {
          MANUAL: '手动',
          SCHEDULE: '调度',
          DEPENDENCY: '依赖'
        };
        return typeMap[row.triggerType] || row.triggerType;
      }
    },
    {
      key: 'duration',
      title: '执行时长',
      align: 'center',
      width: 120,
      render: row => {
        if (!row.duration) return '-';
        const seconds = Math.floor(row.duration / 1000);
        const minutes = Math.floor(seconds / 60);
        const hours = Math.floor(minutes / 60);
        if (hours > 0) {
          return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
        }
        if (minutes > 0) {
          return `${minutes}m ${seconds % 60}s`;
        }
        return `${seconds}s`;
      }
    },
    {
      key: 'retryCount',
      title: '重试次数',
      align: 'center',
      width: 100
    },
    {
      key: 'startTime',
      title: '开始时间',
      align: 'center',
      width: 180
    },
    {
      key: 'operate',
      title: '操作',
      align: 'center',
      width: 280,
      render: row => {
        return h(NSpace, { justify: 'center' }, () => [
          ...(row.status === 'RUNNING' ? [
            h(NPopconfirm, { onPositiveClick: () => handleStop(row.id) }, {
              default: () => '确认停止',
              trigger: () => h(NButton, { size: 'small', type: 'warning' }, () => '停止')
            })
          ] : []),
          h(NButton, { size: 'small', onClick: () => handleRerun(row.id) }, () => '重跑'),
          h(NButton, { size: 'small', onClick: () => handleSync(row.id) }, () => '同步'),
          h(NButton, { size: 'small', type: 'info', onClick: () => handleViewLogs(row.id) }, () => '日志')
        ]);
      }
    }
  ]
});

async function handleStop(instanceId: number) {
  await stopJobInstance(instanceId);
  window.$message?.success('已停止作业实例');
  getData();
}

async function handleRerun(instanceId: number) {
  await rerunJobInstance(instanceId);
  window.$message?.success('已重新启动作业');
  getData();
}

async function handleSync(instanceId: number) {
  await syncJobInstanceStatus(instanceId);
  window.$message?.success('已同步状态');
  getData();
}

function handleViewLogs(instanceId: number) {
  selectedInstanceId.value = instanceId;
  logModalVisible.value = true;
}

watch(visible, () => {
  if (visible.value && props.jobId) {
    getData();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :width="1200" placement="right">
    <NDrawerContent title="作业实例列表" :native-scrollbar="false" closable>
      <NCard :bordered="false" size="small">
        <template #header-extra>
          <NButton @click="getData">
            <template #icon>
              <icon-ic-round-refresh />
            </template>
            刷新
          </NButton>
        </template>
        <NDataTable
          :columns="columns"
          :data="data"
          size="small"
          :scroll-x="1000"
          :loading="loading"
          remote
          :row-key="row => row.id"
          :pagination="mobilePagination"
        />
        <template #footer>
          <TableFooterPagination v-model:pagination="pagination" :loading="loading" @change="getDataByPage" />
        </template>
      </NCard>
    </NDrawerContent>
  </NDrawer>
  <InstanceLogModal v-model:visible="logModalVisible" :instance-id="selectedInstanceId" />
</template>

<style scoped></style>
